import config from '@/config'
import router from '@/router'
import {Message} from 'element-ui'

const axios = require('axios').create({
  baseURL: config.baseURL, //api请求的baseURL
  timeout: 18000, // 超时时间
  // withCredentials: true, // 允许跨域 cookie
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  },
  maxContentLength: 2000,
  transformResponse: [data => {
    try {
      data = JSON.parse(data)
    } catch (e) {
      data = {}
    }
    // 判断登录信息是否有效 登录失效 清除用户信息
    if (data.code && data.code === 'repeat_login_error') {
      Message({
        message: data.data,
        type: 'error',
        duration: 3000
      })
      router.push('/logout')
    }
    return data
  }]
})

axios.interceptors.request.use(request => {
  return request
}, error => {
  return Promise.reject(error)
})

//添加响应拦截器
axios.interceptors.response.use(response => {
  return response
}, error => {
  let array = error.config.url.split("/")
  // 特殊处理 支付 网络问题
  if (array[array.length - 1] === "orderPay") {
    Message({
      message: "网络错误，请查看交易是否成功！",
      type: 'error',
      duration: 2000
    })
  } else {
    // //网络请求发起失败
    if (error.message === "Network Error") {
      let url = error.config.url.split('/'), name = ''
      name = url[url.length - 1]
      // 频繁使用的定时器接口 请求超时不显示网络错误
      if (name === 'getExpectAndDiffTime') {
        return false
      } else {
        Message({
          message: "网络已断开,请稍后再试",
          type: 'error',
          duration: 2000
        })
      }
    }
    // 判断请求超时
    // let originalRequest = error.config
    if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
      Message({
        message: "请求超时了,请重试或者刷新页面试试",
        type: 'error',
        duration: 2000
      })
      // 很有可能导致重复下单
      // return service.request(originalRequest)//再重复请求一次
    }
  }
  return Promise.reject(error)
})
export const get = (url, data) => {
  return axios.get(url, {params: data})
}
export const getId = (url, data) => {
  return axios.get(url + '/' + data)
}
export const post = (url, data) => {
  return axios({
    method: 'post',
    url: url,
    data: data || {}
  })
}